﻿using MengXunAppTool.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MengXunAppTool.DAL
{
    public class RunDAL
    {
        private Sql3Helper sqlHelper = new Sql3Helper();
        public List<Sql3Helper.MX_AppRunRecord> GetApps(string cus)
        {
            return sqlHelper.db.Queryable<Sql3Helper.MX_AppRunRecord>().Where(it=>it.Customer==cus).ToList();
        }
        public Sql3Helper.MX_AppRunRecord GetAppLastRun(string cus, string pro, string name)
        {
            return sqlHelper.db.Queryable<Sql3Helper.MX_AppRunRecord>().Where(it => it.Customer == cus && it.Product == pro && it.AppName == name).OrderBy(it=>it.RunTime,SqlSugar.OrderByType.Desc).First();
        }
        public bool InsertMX_AppRunRecord(Sql3Helper.MX_AppRunRecord mX_Run)
        {
            mX_Run.RunTime = sqlHelper.db.GetDate();
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipaddress = mX_Run.Customer.Contains("海康") ? ipHost.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork && x.ToString().Contains("10.100."))
                : ipHost.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork && x.ToString().Contains("192.168."));
            //IP 版本 4 的地址。IP 版本 6 的地址使用InterNetworkV6
            if (ipaddress==null)
            {
                ipaddress = ipHost.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
            }
            mX_Run.IP = ipaddress.ToString();
            if (sqlHelper.db.Insertable(mX_Run).ExecuteCommand() != 1)
            {
                return false;
            }
            return true;
        }
    }
}
